<?php

/**
 * 杭州橙子 SDK
 * @author chenyun
 */

namespace App\Service\VendorClient\Shopchengzi;

use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;
use Service\AppService\IdService;

class ShopchengziApiClient
{
    private $account  = 'shopchengzi';
    protected $config;
    protected $RouteMap = [
        'createOrder'          => '/order/create_order.do',
        'queryGoodsList'       => '/item/get_item_list.do',
        'orderExpress'         => '/item/get_item_list.do',
    ];
    /**
     * 初始参数
     */
    public function __construct( $apiBody = [] ) 
    {
        $this->config = $apiBody;
    }
    
    /**
     * 创建订单
     */
    public function createOrder( $params = [] ) 
    {   
        ini_set('serialize_precision', 16);
        
        if( empty($params['supplierOrder']) || empty($params['orderGoods']) || empty($params['order']) || empty($params['binfo']) ) {
            return Normal::returnCode(Normal::FAIL,"except param supplierOrder or orderGoods or order or binfo");
        }
        //组装订单参数
        $orderInfo = $params['supplierOrder'];
        $order     = $params['order'];
        $binfo     = $params['binfo'];
        //运费
        $deliver_money  = $orderInfo['deliver_money'];
        $costPriceTotal = 0;
        //商品下单组
        $skuList = [];
        foreach ($params['orderGoods'] as $key => $item )
        {
            //卖价
            $costprice          = $item['costprice'];
            //商品购买数量(下单数量 X 起售数量)
            $quantity           = $item['quantity'];
            //商品组
            $skuList[] = [
                'itemCode'     => $item["supplier_skucode"],
                'buyNum'       => $quantity,
            ];
            $costPriceTotal = bcadd($costPriceTotal, bcmul($costprice, $quantity,2),2);
        }
        
        //创建订单数据
        $data = [
            'appId'         => $this->config["appId"],
            'name'          => $orderInfo['receive_name'],
            'phone'         => $orderInfo['recveive_phone'],
            'province'      => $orderInfo['province'],
            'city'          => $orderInfo['city'],
            'district'      => $orderInfo['district'],
            'address'       => $orderInfo['receive_address'],
            'idCardNumber'  => $orderInfo['buyer_idcard'],
            'userOrderNum'  => $orderInfo['supplier_dsn'],
            'price'         => (string)$costPriceTotal,
            'desc'          => $orderInfo['order_remark'],
            'skuList'       => $skuList
        ];
        $requestParam = [
            'method'    => 'createOrder',
            'data'      => $data
        ];
        $res= $this->execute($requestParam);

        if( $res['code'] == Normal::SUC ) {
            return Normal::returnCode(Normal::SUC,"订单推送成功",[
                'thirdpart_order_sn' => $res["data"]['orderNum']
            ]);
        }
        return $res;
    }
   
    /**
     * 查询商品信息
     */
    public function queryGoodsList( $params = [] )
    {
        $data = [
            'appId'  => $this->config["appId"],
            'page'   => $params['page']  ?? 1,
            'limit'  => $params["limit"] ?? 100,
        ];
        $requestParam = [
            'method'    => 'queryGoodsList',
            'data'      => $data,
        ];
        $response  = $this->execute($requestParam);
        if ($response['code'] != Normal::SUC) {
            $result = ['total' => count([]), 'data' => [], 'response' => $response];
            return Normal::returnCode(Normal::FAIL, "当前分类数据获取异常", $result);
        }
        if (empty($response['data'])) {
            $result = ['total' => count([]), 'data' => [], 'response' => $response];
            return Normal::returnCode(Normal::SUC, "当前分类商品分页获取完成", $result);
        }
        //开始组装数据
        $newData = [];
        $goodsList=$response["data"]["itemList"];
        foreach ($goodsList as $k =>$v){
            //只捞取上架的，并且非预售，并且非赠品的商品
            if($v["shelfStatus"]==1 && $v["gift"] ==0 && $v["presell"]==0 && $v["skuList"]){
                foreach ($v["skuList"] as $skuList =>$sku){
                    foreach ($sku["skuChannels"] as $skuChannels =>$Channel){
                        $newData[]=[
                            'brandName'     => $v["brandName"]??'',
                            'richDesc'      => $v['richDesc']??'',
                            'firstCateId'   => $v["firstCateId"]??'',
                            'firstCateName' => $v["firstCateName"]??'',
                            'id'            => $v["id"],
                            'imageList'     => $v["imageList"],
                            'name'          => $v["name"],
                            'thirdCateName' => $v["thirdCateName"]??'',
                            'channelName'   => $Channel["channelName"]??'',
                            'itemCode'      => $Channel["itemCode"],
                            'price'         => $Channel["price"],
                            'stock'         => $Channel["stock"],
                            'skuValues'     => $sku["skuValues"]??[],
                            'unit'          => $sku["unit"] ?? '',
                            'unitQuantity'  => $sku["unitQuantity"] ?? 1,
                            'weight'        => $sku["weight"] ?? 0,
                            'upc'           => $sku["upc"] ?? $Channel["itemCode"],
                        ];
                    }
                } 
            }
        }
        $result = ['total' => count($newData),'data' => $newData];
        return Normal::returnCode(Normal::SUC, '获取成功', $result);
    }
    /**
     * 加签
     * @param array $param
     */
    protected function getToken($param)
    {
        //加签算法为：md5( 拼接（所有请求参数转为json字符串，secret）)
        $jsonStr=json_encode($param);
        $Sign = md5($jsonStr.$this->config["secret"]);
        return $Sign;
    }

    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )  
    {
        if(empty($param['data']) ) {
            return Normal::returnCode(Normal::FAIL,"数据不能为空");
        }
        
        $method = $param['method'];
        $url = $this->config['baseurl'].$this->RouteMap[$method];
        $Sign=$this->getToken($param["data"]);
        $parameter = [
            [
                'tag'       => $this->account.'_'.$method,
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => $param['data'],
                'method'    => 'post',
                'format'    => 'json',
                'header'    => [
                    "SIGN:{$Sign}",
                    "Content-Type:application/json",
                    "Accept:application/json",
                    "Accept-Encoding:utf-8"
                ],
        
            ],
        ];
        
        if( in_array($method,['queryGoodsList']) ) {
            $resTask = TaskWorker::instance()->addTask($parameter,'handleDiableTask');
        } else {
            $resTask = TaskWorker::instance()->addTask($parameter);
        }
        $resTask = current($resTask);
        $res     = $resTask['response']['result'];  
        $resHttp = json_decode($res,true);
        if(isset($resHttp['success']) && $resHttp['success'] == 1 ) {
            return Normal::returnCode(Normal::SUC,"操作成功",$resHttp["data"]);
        }
        $message = isset($resHttp['message']) ? $resHttp['message'] : '请求失败';
        return Normal::returnCode(Normal::FAIL,$message);
    }
}